package cao.oschina.function.me.notice;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import cao.oschina.R;
import cao.oschina.activity.ToolBarActivity;
import cao.oschina.api.Api;
import cao.oschina.api.URLs;
import cao.oschina.bean.Active;
import cao.oschina.function.multiple.blog.BlogDetail;
import cao.oschina.function.multiple.news.NewsDetail;
import cao.oschina.util.FileUtils;
import cao.oschina.util.TimeUtil;
import cao.oschina.widget.PushDownListView;
import cao.oschina.widget.RefreshView;
import hd.util.ToastUtil;
import hd.util.adapter.BaseViewHolder;
import hd.util.adapter.UniAdapter;
import hd.util.http.HttpResponse;
import hd.util.load.ImageLoader;
import hd.util.widget.listview.BasePushDownListView;
import hd.util.xml.XmlParser;

/**
 * @ @我
 * Created by Haidy on 15/4/11.
 */
public class AtMeFunction extends NoticeFunction {

    private PushDownListView listView;
    private AtMeAdapter adapter;

    public AtMeFunction(View view, ToolBarActivity activity) {
        super(view, activity);
    }

    @Override
    protected void initView() {
        listView = (PushDownListView) view.findViewById(R.id.at_me_list_view);
        listView.setAdapter(adapter = new AtMeAdapter(activity));
        listView.setOnRefreshListener(new PushDownListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isLoading) {
                    pageIndex = 0;
                    loadData(true);
                }
            }
        });
        listView.setOnLoadNextPageListener(new BasePushDownListView.OnLoadNextPageListener() {
            @Override
            public void onLoad() {
                if (!isLoading && !getAll) {
                    pageIndex++;
                    loadData(false);
                }
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (adapter.getCount() > 1 && position != adapter.getCount() - 1) {
                    Intent intent = new Intent();
                    Active active = adapter.getItem(position - 1);
                    System.out.println(active.objecttype);
                    if (active.objecttype == 18) {
                        intent.setClass(activity, BlogDetail.class);
                    } else if (active.objecttype == 16) {
                        intent.setClass(activity, NewsDetail.class);
                    } else if (active.objecttype == 17) {//帖子
//                        intent.setClass(activity,
                        return;
                    }
                    intent.putExtra("id", active.objectID);
                    intent.putExtra("comment_count", active.commentCount);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    view.getContext().startActivity(intent);
                    activity.activityPushAnim();
                }
            }
        });
    }

    @Override
    protected void initData() {
        loadData(true);
    }

    /**
     * 加载数据
     *
     * @param refresh 是否刷新
     */
    private void loadData(final boolean refresh) {
        listView.setEnabled(false);
        isLoading = true;
        Api.loadData(false, app.getConfig(), URLs.ACTIVE_LIST + "?catalog=2&pageIndex=" + pageIndex + "&pageSize=20&uid=" + app.getConfig().getUid(), new Api.OnApiListener<HttpResponse>() {
            @Override
            public void result(boolean statue, HttpResponse data) {
                if (statue) {
                    List<Active> activeList = new XmlParser<Active>(data.text, Active.class).parser("active");
                    if (refresh) {
                        adapter.setData(activeList);
                    } else {
                        if (adapter.getCount() != 0) {
                            adapter.remove(adapter.getCount() - 1);
                        }
                        adapter.addAllData(activeList);
                    }
                    if (activeList.size() < 20) {
                        getAll = true;
                    }
                    activeList.clear();
                    adapter.addData(null);
                    listView.overHeadScroll();
                } else {
                    ToastUtil.toastShort(data.info);
                }
                listView.setEnabled(true);
                isLoading = false;
            }
        });

    }

    private class AtMeAdapter extends UniAdapter<Active, ViewHolder> {

        private ImageLoader imageLoader;

        public AtMeAdapter(Context context) {
            super(context);
            imageLoader = new ImageLoader();
        }

        @Override
        public int getContentView() {
            return R.layout.at_me_item_view;
        }

        @Override
        public BaseViewHolder<Active, ViewHolder> getHolder() {
            return new BaseViewHolder<Active, ViewHolder>() {
                @Override
                public void loadData(ViewHolder holder, Active data, int position) {
                    if (data != null) {
                        if (holder.itemView.getVisibility() == View.GONE) {
                            holder.itemView.setVisibility(View.VISIBLE);
                            holder.nextPageView.setVisibility(View.GONE);
                            holder.refreshView.stopRotation();
                        }
                        Spanned spanned = createTitle(data);
                        holder.titleView.setText(spanned);
                        holder.messageView.setText(data.message);
                        holder.authorView.setText(data.author);
                        holder.pubDateView.setText(TimeUtil.friendTime(data.pubDate));
                        holder.commentCountView.setText(data.commentCount);
                        loadHeadView(holder.headView, data.portrait);
                    } else {
                        if (holder.nextPageView.getVisibility() == View.GONE) {
                            holder.itemView.setVisibility(View.GONE);
                            holder.nextPageView.setVisibility(View.VISIBLE);
                            if (getAll) {
                                holder.refreshView.setVisibility(View.GONE);
                                holder.refreshTextView.setText(app.getString(R.string.get_all_data));
                            } else {
                                holder.refreshTextView.setText(app.getString(R.string.loading_next_pager));
                                holder.refreshView.setVisibility(View.VISIBLE);
                                holder.refreshView.startRotation();
                            }
                        }
                    }
                }

                private Spanned createTitle(Active active) {
                    StringBuilder html = new StringBuilder();
                    if (active.objecttype == 16) {//新闻
                        html.append("在新闻 ");
                    } else if (active.objecttype == 18) {//博客
                        html.append("在博客 ");
                    }
                    html.append("<a href=\"")
                            .append(active.objectID)
                            .append("\">")
                            .append(active.objecttitle)
                            .append("</a>");
                    html.append(" 发表");
                    return Html.fromHtml(html.toString());
                }

                private void loadHeadView(ImageView headView, String portrait) {
                    imageLoader.loadImage(portrait, headView, new ImageLoader.OnImageCacheLoaderListener() {
                        @Override
                        public String onSDCardCache(String url) {
                            return FileUtils.getHeadImagePath(activity, url);
                        }
                    });
                }
            };
        }

        @Override
        public ViewHolder initViewHolder(View convertView) {
            return new ViewHolder(convertView);
        }
    }

    private class ViewHolder {

        public final ImageView headView;
        public final TextView authorView;
        public final TextView pubDateView;
        public final TextView titleView;
        public final TextView messageView;
        public final TextView commentCountView;

        public final View itemView;
        public final View nextPageView;
        public final RefreshView refreshView;
        public final TextView refreshTextView;

        public ViewHolder(View view) {
            headView = (ImageView) view.findViewById(R.id.head_view);
            authorView = (TextView) view.findViewById(R.id.author);
            pubDateView = (TextView) view.findViewById(R.id.pub_date);
            titleView = (TextView) view.findViewById(R.id.title);
            messageView = (TextView) view.findViewById(R.id.content);
            commentCountView = (TextView) view.findViewById(R.id.comment_count);

            itemView = view.findViewById(R.id.item_view);
            nextPageView = view.findViewById(R.id.next_pager);
            refreshView = (RefreshView) view.findViewById(R.id.next_pager_refresh_view);
            refreshTextView = (TextView) view.findViewById(R.id.pager_text_view);
        }
    }
}
